package cn.hicard.auth.web.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.hicard.auth.entity.MgRoleSource;
import cn.hicard.auth.entity.MgRoleSourceId;
import cn.hicard.auth.entity.MgRoleinfo;
import cn.hicard.auth.entity.MgUserinfo;
import cn.hicard.auth.service.RoleinfoService;
import cn.hicard.auth.service.SourceService;
import cn.hicard.auth.service.UserinfoService;
import cn.hicard.auth.web.AuthFilter;
import cn.hicard.auth.web.Node;
import cn.hicard.auth.web.util.WebUI;

@Controller
@RequestMapping("/auth/role")
public class RoleinfoCtrl {
	
	public static final String TYPE_SOURCE = "1";
	public static final String TYPE_MENU = "2";
		
	/************** ↓↓↓↓  角色自身的数据管理  ↓↓↓↓ **************/
	@Autowired	
	private RoleinfoService roleinfoService;
	@Autowired
	private UserinfoService userinfoService;
	@Autowired
	private SourceService sourceService;
	
	
	/**
	 * 加载角色信息列表
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public String list(HttpSession session, ModelMap map) throws Exception{
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);
		List<MgRoleinfo> roles;
		// A.如果是超级管理员，则可以查询所有的角色
		if(UserinfoCtrl.UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			roles = roleinfoService.getAll();
		}
		// B.如果是其它管理员，则只能分配自己拥有的角色（注：非管理员无法访问）
		else{
			roles = roleinfoService.getByUser(logonUser.getPkUserinfo());
		}
		map.put("list", roles);
		return "/auth/role";
	}
	
	/**
	 * 页面刷新
	 * @return
	 */
	@RequestMapping(value="/refresh.do")
	public String refresh() {
		return "redirect:/auth/role.do";
	}
	
	/**
	 * 保存
	 * @param rolename
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/save.do", method=RequestMethod.POST)
	public String save(@RequestParam("rolename")String rolename,
			@RequestParam("roletype")String roletype) throws Exception{
		MgRoleinfo role = new MgRoleinfo();
		role.setRolename(rolename);
		role.setRoletype(roletype);
		roleinfoService.save(role);
		return "redirect:/auth/role.do";
	}
	
	/**
	 * 删除
	 * @param pkRoleinfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/delete.do", method=RequestMethod.POST)
	public String delete(@RequestParam("pkRoleinfo")int pkRoleinfo) throws Exception{
		roleinfoService.delete(pkRoleinfo);
		return "redirect:/auth/role.do";
	}
	
	/**
	 * 更新
	 * @param pkRoleinfo
	 * @param rolename
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/update.do", method=RequestMethod.POST)
	public String update(
			@RequestParam("pkRoleinfo")int pkRoleinfo,
			@RequestParam("rolename")String rolename) throws Exception{
		MgRoleinfo role = roleinfoService.getByPk(pkRoleinfo);
		role.setRolename(rolename);
		roleinfoService.update(role);
		return "redirect:/auth/role.do";
	}
	/************** ↑↑↑↑  角色自身的数据管理  ↑↑↑↑ **************/
	


	
	
	
	
	
	
	/************** ↓↓↓↓  角色分配资源  ↓↓↓↓ **************/
	
	/** 系统根资源，包含所有已注册的资源 */
	public static final String ROOT_TREE = "root_tree";
	

	/**
	 * 为角色分配资源，加载总的树的结构
	 * @throws Exception 
	 */
	@RequestMapping("/allot.do")
	public String loadAllot(HttpSession session,
			@RequestParam("pk")int pkRoleinfo,
			ModelMap map) throws Exception {
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);		
	
		// 当前要分配资源的Roleinfo对象
		MgRoleinfo role = roleinfoService.getByPk(pkRoleinfo);
		map.addAttribute("role", role);
		// 查询要分配的角色已拥有的资源
		List<Integer> selectedPks =  roleinfoService.findOwnSourcePks(pkRoleinfo);
		//  固定：1-权限角色-系统入口； 2-菜单角色-菜单入口；
		Node treeNode = null;
		// [超级管理员]无限制的加载总资源Tree
		if(UserinfoCtrl.UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			if(TYPE_SOURCE.equals(role.getRoletype())){
				treeNode = sourceService.findNodeByType(AuthFilter.ROOT_SOURCE_PK, null);
			}else if(TYPE_MENU.equals(role.getRoletype())){
				treeNode = sourceService.findNodeByType(AuthFilter.ROOT_MENU_PK, null);
			}
		}
		// 普通管理员只能加载自己拥有的资源Tree
		else{
			List<Integer> ownRolePks = userinfoService.findOwnRolePks(logonUser.getPkUserinfo());			
			if(TYPE_SOURCE.equals(role.getRoletype())){
				treeNode = sourceService.findNodeByRoles(AuthFilter.ROOT_SOURCE_PK, ownRolePks);
			}else if(TYPE_MENU.equals(role.getRoletype())){
				treeNode = sourceService.findNodeByRoles(AuthFilter.ROOT_MENU_PK, ownRolePks);
			}
		}

		
		// (4)构建根资源的HTML树形结构，同时把角色的资源在总树资源上标识出来
		if (treeNode != null) {
			String treeHtml = WebUI.buildSelectTree(treeNode, selectedPks,"'leafClickHandler(this)'","'selecterClickHandler(this)'");
			map.addAttribute("tree", treeHtml);
		} else {
			map.addAttribute("tree", "数据tree为空");
		}		
		return "/auth/allotsource";
	}
	
	/**
	 * 保存角色资源分配
	 * @param pkRoleinfo
	 * @param sources
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/saveallot")
	public String saveAllot(
			@RequestParam("pkRoleinfo")int pkRoleinfo,
			@RequestParam(required=false, value="sources")int[] pkSources) throws Exception{
		if(pkSources==null)pkSources = new int[0];
		List<MgRoleSource> rslist  = new ArrayList<MgRoleSource>(pkSources.length);
		for (int rs : pkSources) {
			MgRoleSource mrs = new MgRoleSource();
			MgRoleSourceId id = new MgRoleSourceId();
			id.setPkRoleinfo(pkRoleinfo);
			id.setPkSource(rs);
			mrs.setId(id);
			rslist.add(mrs);
		}
		// 保存新分配的
		roleinfoService.saveRoleSource(pkRoleinfo, rslist);
		return "redirect:/auth/role.do";
	}
	/************** ↑↑↑↑  角色分配资源  ↑↑↑↑ **************/
}
